<template>
  <div class="treatment-templates">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>治疗模板</span>
          <el-button v-if="activeTab === 'system'" type="primary" @click="openTemplateDialog()">新建模板</el-button>
        </div>
      </template>
      
      <!-- 模板类型标签页 -->
      <div class="template-tabs">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="系统模板" name="system"></el-tab-pane>
          <el-tab-pane label="用户模板" name="user"></el-tab-pane>
        </el-tabs>
      </div>
      
      <!-- 模板类型筛选 -->
      <div class="template-filters" v-if="activeTab === 'system'">
        <el-radio-group v-model="currentTemplateType" @change="loadTemplateList">
          <el-radio-button label="">全部</el-radio-button>
          <el-radio-button label="hospital">医院</el-radio-button>
          <el-radio-button label="school">学校</el-radio-button>
          <el-radio-button label="enterprise">企业</el-radio-button>
          <el-radio-button label="research">科研</el-radio-button>
        </el-radio-group>
      </div>
      
      <el-table :data="templateList" v-loading="loading" stripe>
        <el-table-column prop="template_name" label="模板名称" width="150" />
        <el-table-column prop="user_id" label="用户id" width="100" v-if="activeTab=='user'"></el-table-column>
        <el-table-column prop="template_type" label="模板类型" width="100" v-else>
          <template #default="{ row }">
            <el-tag :type="getTemplateTypeTag(row.template_type)">
              {{ getTemplateTypeText(row.template_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="treatment_mode" label="治疗模式" width="120" />
        <el-table-column prop="treatment_duration" label="默认时长" width="100">
          <template #default="{ row }">
            {{ (row.treatment_duration) }}分钟
          </template>
        </el-table-column>
        <el-table-column prop="current_intensity" label="电流强度" width="100" />
        <el-table-column prop="frequency" label="频率" width="100" />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="viewTemplate(row)">查看</el-button>
            <el-button v-if="activeTab === 'system'" size="small" @click="editTemplate(row)">编辑</el-button>
            <!-- <el-button size="small" type="primary" @click="applyTemplate(row)">应用</el-button> -->
            <el-button v-if="activeTab === 'system'" size="small" type="danger" @click="handleDeleteTemplate(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 模板查看对话框 -->
    <el-dialog 
      :title="viewDialogTitle" 
      v-model="viewDialogVisible" 
      width="500px"
    >
      <el-form 
        :model="viewTemplateForm" 
        label-width="140px"
      >
        <el-form-item label="模板名称">
          <el-input v-model="viewTemplateForm.template_name" readonly />
        </el-form-item>
        
        <el-form-item label="模板类型">
          <el-select v-model="viewTemplateForm.template_type" disabled>
            <el-option label="医院" value="hospital" />
            <el-option label="学校" value="school" />
            <el-option label="企业" value="enterprise" />
            <el-option label="科研" value="research" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="治疗模式">
          <el-select v-model="viewTemplateForm.treatment_mode" disabled>
            <el-option label="tDCS+" value="tDCS+" />
            <el-option label="tDCS-" value="tDCS-" />
            <el-option label="tACS" value="tACS" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="默认时长">
          <el-input-number 
            v-model="viewTemplateForm.treatment_duration" 
            :min="10" 
            :max="30" 
            controls-position="right"
            disabled
          />&nbsp;&nbsp;&nbsp; 分
        </el-form-item>
        
        <el-form-item label="默认强度(mA)">
          <el-input-number 
            v-model="viewTemplateForm.current_intensity" 
            :min="0" 
            :max="2" 
            :step="0.04"
            disabled
          />
        </el-form-item>
        
        <el-form-item label="频率" v-if="viewTemplateForm.treatment_mode == 'tACS'">
          <el-input-number 
            v-model="viewTemplateForm.frequency" 
            :min="0" 
            :max="100" 
            :step="0.1"
            disabled
          /> Hz
        </el-form-item>
        
        <el-form-item label="设为默认">
          <el-switch v-model="viewTemplateForm.is_default" disabled />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 模板编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="500px"
      @close="resetForm"
    >
      <el-form 
        ref="templateFormRef" 
        :model="templateForm" 
        :rules="templateRules" 
        label-width="140px"
      >
        <el-form-item label="模板名称" prop="template_name">
          <el-input v-model="templateForm.template_name" />
        </el-form-item>
        
        <el-form-item label="模板类型" prop="template_type">
          <el-select v-model="templateForm.template_type" placeholder="请选择模板类型">
            <el-option label="医院" value="hospital" />
            <el-option label="学校" value="school" />
            <el-option label="企业" value="enterprise" />
            <el-option label="科研" value="research" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="治疗模式" prop="treatment_mode">
          <el-select v-model="templateForm.treatment_mode" placeholder="请选择治疗模式">
            <el-option label="tDCS+" value="tDCS+" />
            <el-option label="tDCS-" value="tDCS-" />
            <el-option label="tACS" value="tACS" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="默认时长" prop="treatment_duration">
          <el-input-number 
            v-model="templateForm.treatment_duration" 
            :min="10" 
            :max="30" 
            controls-position="right"
          />&nbsp;&nbsp;&nbsp; 分
        </el-form-item>
        
        <el-form-item label="默认强度(mA)" prop="current_intensity">
          <el-input-number 
            v-model="templateForm.current_intensity" 
            :min="0" 
            :max="2" 
            :step="0.04"
          />
        </el-form-item>
        
        <el-form-item label="频率" prop="frequency" v-if="templateForm.treatment_mode == 'tACS'">
          <el-input-number 
            v-model="templateForm.frequency" 
            :min="0" 
            :max="100" 
            :step="0.1"
          /> Hz
        </el-form-item>

        <el-form-item label="设为默认" prop="is_default">
          <el-switch v-model="templateForm.is_default" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTemplate">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getTemplateList, createTemplate, updateTemplate, deleteTemplate } from '@/api/treatment'
import { formatDate, formatDuration } from '@/utils/format'

interface Template {
  id: number
  template_name: string
  template_type: string
  treatment_mode: string
  treatment_duration: number
  current_intensity: number
  frequency: number
  is_default: boolean
  created_at: string
}

const loading = ref(false)
const templateList = ref<Template[]>([])
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)
const currentTemplateId = ref<number | null>(null)
const activeTab = ref('system') // 默认显示系统模板

const templateFormRef = ref<FormInstance>()
const templateForm = reactive({
  template_name: '',
  template_type: 'hospital',
  treatment_mode: '',
  treatment_duration: 600,
  current_intensity: 1.0,
  frequency: 10,
  is_default: false
})

const viewTemplateForm = reactive({
  template_name: '',
  template_type: 'hospital',
  treatment_mode: '',
  treatment_duration: 600,
  current_intensity: 1.0,
  frequency: 10,
  is_default: false
})

const templateRules = {
  template_name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' }
  ],
  treatment_mode: [
    { required: true, message: '请选择治疗模式', trigger: 'change' }
  ],
  treatment_duration: [
    { required: true, message: '请输入默认时长', trigger: 'blur' }
  ],
  current_intensity: [
    { required: true, message: '请选择默认强度', trigger: 'change' }
  ]
}

const dialogTitle = computed(() => {
  return isEdit.value ? '编辑模板' : '新建模板'
})

const viewDialogTitle = computed(() => {
  return '查看模板'
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const currentTemplateType = ref('')

// 处理标签页切换
const handleTabChange = (tabName: string) => {
  activeTab.value = tabName
  pagination.currentPage = 1 // 切换标签页时重置到第一页
  loadTemplateList()
}

// 查看模板
const viewTemplate = (template: Template) => {
  Object.assign(viewTemplateForm, template)
  viewDialogVisible.value = true
}

const loadTemplateList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      template_type: currentTemplateType.value,
      type: activeTab.value // 添加类型参数：system 或 user
    }
    const response: any = await getTemplateList(params)
    templateList.value = response.records
    pagination.total = response.total
  } catch (error) {
    ElMessage.error('获取模板列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const openTemplateDialog = (template?: Template) => {
  if (template) {
    isEdit.value = true
    currentTemplateId.value = template.id
    Object.assign(templateForm, template)
  } else {
    isEdit.value = false
    currentTemplateId.value = null
    resetForm()
  }
  dialogVisible.value = true
}

const handleDeleteTemplate = async (template: Template) => {
  ElMessageBox.confirm('确定要删除该模板吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteTemplate(template.id)
      ElMessage.success('模板删除成功')
      loadTemplateList()
    } catch (error) {
      ElMessage.error('模板删除失败')
      console.error(error)
    }
  })
}

const editTemplate = (template: Template) => {
  openTemplateDialog(template)
}

const applyTemplate = (template: Template) => {
  ElMessage.success(`已应用模板: ${template.template_name}`)
  // 这里应该跳转到治疗页面并应用模板
}

const getTemplateTypeTag = (type: string): any => {
  const typeMap: Record<string, string> = {
    hospital: 'primary',
    school: 'success',
    enterprise: 'warning',
    research: 'info'
  }
  return typeMap[type] || 'info'
}

const getTemplateTypeText = (type: string) => {
  const textMap: Record<string, string> = {
    hospital: '医院',
    school: '学校',
    enterprise: '企业',
    research: '科研'
  }
  return textMap[type] || type
}

const saveTemplate = async () => {
  if (!templateFormRef.value) return
  
  await templateFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      if (isEdit.value && currentTemplateId.value) {
        await updateTemplate(currentTemplateId.value, templateForm)
        ElMessage.success('模板更新成功')
      } else {
        await createTemplate(templateForm)
        ElMessage.success('模板创建成功')
      }
      
      dialogVisible.value = false
      loadTemplateList()
    } catch (error) {
      ElMessage.error('保存模板失败')
      console.error(error)
    }
  })
}

const resetForm = () => {
  Object.assign(templateForm, {
    template_name: '',
    treatment_mode: '',
    treatment_duration: 600,
    current_intensity: 50,
    frequency: 10,
    is_default: false
  })
  
  if (templateFormRef.value) {
    templateFormRef.value.resetFields()
  }
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadTemplateList()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadTemplateList()
}

onMounted(() => {
  loadTemplateList()
})
</script>

<style scoped lang="scss">
.treatment-templates {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .template-tabs {
    margin-bottom: 20px;
  }
  
  .template-filters {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>